#!/usr/bin/python3
import pygame
from pygame.locals import *
import struct

# 定义颜色
WHITE = (200, 200, 200)
BLACK = (0, 0, 0)
# 初始化pygame
pygame.init()

# 加载bmp图片
image = pygame.image.load('out.bmp')
img_size = image.get_size()
# 创建一个窗口，大小与图片相同
screen = pygame.display.set_mode(img_size)

def save_circles_to_file(circles, filename="save.txt"):
    with open(filename, 'w') as f:
        for circle in circles:
            rect = circle[0]
            x, y = rect.x, rect.y
            f.write(f"{x}, {y}\n")  # 将每个圆的x和y坐标写入文件，并在每行结尾添加换行符

def load_circles_from_file(filename="save.txt"):
    size = 15
    circles_info = []
    try:
        with open(filename, 'r') as f:
            for line in f.readlines():
                x, y = map(int, line.strip().split(', '))
                circles_info.append((pygame.Rect(x, y, size, size), False))
    except FileNotFoundError:
        print(f"File {filename} not found.")
        return [(pygame.Rect(50+50*(y//25), y%25*25+50, size, size), False) for y in range(25*4+4)]

    return circles_info

# 
circles = load_circles_from_file()

# 加载系统默认的无衬线字体，设置字号
font = pygame.font.SysFont(None, 25)

# 转换为色块编号
def to_index(a):
    if a <= 22*4:
        return a//4
    elif a//4 == 23:
        return 24
    elif a//4 == 24:
        return 26
    elif a == 100 or a == 101:
        return 23            
    elif a == 102 or a == 103:
        return 25


running = True
savemode = False
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            for i, (circle, is_pressed) in enumerate(circles):
                if circle.collidepoint(event.pos):
                    circles[i] = (circle, True)  # 圆圈被按下，记录其状态为True

        elif event.type == pygame.MOUSEBUTTONUP:
            for i, (circle, is_pressed) in enumerate(circles):
                if is_pressed:
                    circles[i] = (circle, False)  # 圆圈被释放，重置其状态为False

        elif event.type == pygame.MOUSEMOTION and any(circle[1] for circle in circles):
            for i, (circle, is_pressed) in enumerate(circles):
                if is_pressed:
                    circle.move_ip(event.rel)  # 更新圆圈位置
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_s:
            save_circles_to_file(circles)
            savemode = True
            print("save to save.txt.")

    if savemode:
        # 清空屏幕
        screen.fill((255, 255, 255))
    else:
        # 将图片加载到窗口上
        screen.blit(image, (0, 0))

    # 绘制所有圆圈及编号
    for i in range(0,25):
        circle0, is_pressed = circles[4*i]
        circle1, is_pressed = circles[4*i+1]
        circle2, is_pressed = circles[4*i+2]
        circle3, is_pressed = circles[4*i+3]
        points = [(circle0.centerx, circle0.centery),
                  (circle1.centerx, circle1.centery),
                  (circle2.centerx, circle2.centery),
                  (circle3.centerx, circle3.centery)]
        index = to_index(4*i)
        if savemode:
            pygame.draw.polygon(screen, (index, index, index), points)
        else:
            pygame.draw.polygon(screen, WHITE, points)
            pygame.draw.polygon(screen, BLACK, points, 1)
            for item in (circle0,circle1,circle2,circle3):
                pygame.draw.circle(screen, WHITE, item.center, item.width//2, 0)  # 白色填充
                pygame.draw.circle(screen, BLACK, item.center, item.width//2, 2)  # 黑色边框
            # 计算编号文本的绘制位置
            text_surface = font.render(str(index), True, BLACK)
            text_rect = text_surface.get_rect(center=(circle3.right + 5, circle3.bottom + 5))
            # 在圆圈旁边绘制编号
            screen.blit(text_surface, text_rect)
    for i in (100,102):
        index = to_index(i)
        circle0, is_pressed = circles[i]
        circle1, is_pressed = circles[i+1]
        if savemode:
            pygame.draw.line(screen, (index, index, index), circle0.center, circle1.center, 16)
        else:
            pygame.draw.line(screen, BLACK, circle0.center, circle1.center, 16)
            pygame.draw.line(screen, WHITE, circle0.center, circle1.center, 14)
            for item in (circle0, circle1):
                pygame.draw.circle(screen, WHITE, item.center, item.width//2, 0)  # 白色填充
                pygame.draw.circle(screen, BLACK, item.center, item.width//2, 2)  # 黑色边框
            # 计算编号文本的绘制位置
            text_surface = font.render(str(index), True, BLACK)
            text_rect = text_surface.get_rect(center=(circle1.right + 5, circle1.bottom + 5))
            # 在圆圈旁边绘制编号
            screen.blit(text_surface, text_rect)
    if savemode:
        with open("cube_face.bin", 'wb') as f:
            print(f"image size is {img_size[0]}, {img_size[1]}")
            print(f"write cube_face.bin")
            for y in range (0, img_size[1]):
                for x in range (0, img_size[0]):
                    c = screen.get_at([x,y])
                    f.write(struct.pack('B', c[0]))
        savemode = False
    # 更新显示
    pygame.display.flip()

# 退出Pygame
pygame.quit()
